<?php
require 'facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => APPID,
  'secret' => SECRET,
  'cookie' => true,
));

$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

if(@$_SESSION['username_email']==''){
if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();

  //CHECK IF USER IN DATABASE
  include_once('db_config/db_user.php');
  $user_fb=new user();
  $rs_fb = $user_fb->uniq_user_list('facebook_id',$me[id]);
  $data_fb = mysql_fetch_array($rs_fb);
  if(!$data_fb){
	//Check if email address is already registered
	$rs_fb = $user_fb->uniq_user_list('user_primary_email',$me[email]);
	$data_fb_email = mysql_fetch_array($rs_fb);
	if(!$data_fb_email){
		$sql="INSERT into ninerr_user set 
			user_fullname='".$me[name]."',
			user_name='".$me[first_name]."',
			user_nickname='".$me[first_name]."',
			user_password='".rand(999,9999999)."',
			user_primary_email='".$me[email]."',
			facebook_id='".$me[id]."'
			";
		mysql_query($sql);
	}
	//User email already in database
	else{
		$sql="UPDATE ninerr_user set 
			facebook_id='".$me[id]."' 
			where user_primary_email='".$me[email]."'
			";
		mysql_query($sql);
	}
  }
  //Now make sure our facebook user is logged in to system
	$_SESSION['username_email']= $me[email];
	$rs_user=$user->uniq_user_list('user_primary_email',$me[email]);
	$data_user=mysql_fetch_array($rs_user);
	$_SESSION['user_id']=$data_user['user_id'];
	$_SESSION['user_name']=$data_user['user_name'];
	header("Location: index.php");
}
}
?>
<!-- facebook BEGIN ==================== -->
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId   : '<?php echo $facebook->getAppId(); ?>',
      session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
      status  : true, // check login status
      cookie  : true, // enable cookies to allow the server to access the session
      xfbml   : true // parse XFBML
    });

    // whenever the user logs in, we refresh the page
    FB.Event.subscribe('auth.login', function() {
      window.location.reload();
    });
  };

  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
</script>
<!-- facebook END ==================== -->
<div id="header" class="clearfix">
	<h1><a href="/" title="esKoosh">esKoosh</a></h1>
	<div id="sub-header">
		<div class="clearfix">
			<!-- search BEGIN ===== -->
			<?php
		if(@$_SESSION['username_email']=='')// if havenot logined yet, then search box display first
		{
		?>
			<form class="search clearfix" method="get" id="" enctype="multipart/form-data" action="search.php">
				<div class="filter-section">
					<div class="input text required">
						<div class="input text"><label>Search</label>
						<input type="text" style="width:215px; border:0px solid #ffffff; height:18px;" name="query"  value="<?php if(@$query) echo $query; else echo 'Search'; ?>" onFocus="if(this.value=='Search') this.value=''" onBlur="if(this.value=='') this.value='Search'"  />				
						</div>							
					</div>
					<div class="submit"><div class="submit"><input type="submit" value="Search" /></div></div>
				</div>
			</form>
			<?php
		}
		?>
			<!-- search END ===== -->
			<!-- menu BEGIN ===== -->
			<ul class="menu clearfix">
				<li class="active"> <a href="index.php">Home</a></li>
	      		<?php
			if(@$_SESSION['username_email']=='')
			{
			?>
			    <!--<li> <a href="how_work.php" >How it Works</a></li>-->
			    <li> <a href="#" id="login_link1">Join</a></li>
			    <li> <a href="#" id="login_link"> Sign In</a></li>
			    <li> <a href="help.php" id="login_link1">Help</a></li>
				<?php
			} else {
			?>
				<li  class="profile"><a href="#" title="Profile">Profile</a>
					<ul class="sub-menu">
						<li><a href="profile_edit.php" title="Settings">Settings</a></li>
						<li><a href="bookmarks.php" title="Favourites">Favourites</a></li>
						<li><a href="messages.php" title="Messages">Messages</a></li>
					</ul>
				</li>
				<li  class="profile"><a href="#" title="Start Building">Start Building</a>
					<ul class="sub-menu">
						<li><a href="user_gigs.php" title="My Boxes<">My Boxes</a></li>
						<li><a href="manage_work.php" title="Built Status">Built Status</a></li>
					</ul>
				</li>
				<li  class="profile"><a href="#" title="Shopping">Shopping</a>
					<ul class="sub-menu">
						<li><a href="manage_order.php" title="Manage Orders">Manage Orders</a></li>
						<li><a href="sales_balance.php" title="Earnings">Earnings</a></li>
					</ul>
				</li>
			    <li><a href="logout.php">Log Out</a></li>
			    <?php
			}
			?>
			</ul>
			<!-- menu END ===== -->
			<!-- search BEGIN ===== -->
			<?php
		if(@$_SESSION['username_email']!='')// if already logined, then search box display after
		{
		?>
			<form class="search clearfix" method="get" id="" enctype="multipart/form-data" action="search.php" style="margin-top:5px">
				<div class="filter-section">
					<div class="input text required">
						<div class="input text"><label>Search</label>
						<input type="text" style="width:215px; border:0px solid #ffffff; height:18px;" name="query"  value="<?php if(@$query) echo $query; else echo 'Search'; ?>" onFocus="if(this.value=='Search') this.value=''" onBlur="if(this.value=='') this.value='Search'"  />				
						</div>							
					</div>
					<div class="submit"><div class="submit"><input type="submit" value="Search" /></div></div>
				</div>
			</form>                                        
			<?php
		}
		?>
			<!-- search END ===== -->
		</div>
		
		<!-- welcome BEGIN ==== -->
    	<p class="welcome-block clearfix clear">
		 <?php
		if(@$_SESSION['username_email']=='')
		{
			echo 'Welcome Back, Guest';
		} else {
			echo 'Welcome Back, <a title="'.$_SESSION['user_name'].'" href="#">'.$_SESSION['user_name'].'</a>';
		}					
		?>
		</p>
		<!-- welcome END ==== -->
		<!-- openid BEGIN ==== -->
		 <?php
	if(@$_SESSION['username_email']=='')
	{
	?>
		<ul class="list clearfix">
		<li class="fbc">
		    <div> 
		        <?php if ($me): ?>
		        <a href="<?php echo $logoutUrl; ?>"> <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif" /> 
		        </a> 
		        <?php else: ?>
		        <fb:login-button perms="email"></fb:login-button> 
		        <?php endif ?>
		    </div>
		
		<li class="face-book">
			<div>							
				<a href="https://www.facebook.com/login.php?api_key=7fa68af5bb94dbc25da468464232bfc4&amp;cancel_url=http%3A%2F%2Fwww.twentyville.com%2Fuser%2Fregister&amp;display=page&amp;fbconnect=1&amp;next=http%3A%2F%2Fwww.twentyville.com%2Fusers%2Fregister&amp;return_session=1&amp;session_version=3&amp;v=1.0&amp;req_perms=email%2Cpublish_stream"><img alt="[Image: Facebook Connect]" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_short.gif" /></a>					
			</div>
		</li>
		<li class="twiiter"><a class="Twitter" href="/users/twitter/login">Sign in with Twitter</a></li>
														
		</ul>
		<?php
	}
	?>
		<!-- openid END ==== -->
	</div><!-- end sub-header -->
</div>
<?php include('login_box.php'); ?>
<?php include('registration_box.php'); ?>